package com.sy.simpleegg.mvp.model

import com.sy.simpleegg.base.BaseModel
import com.sy.simpleegg.bean.ClearDataBean
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.mvp.contract.FastManageContract
import com.sy.simpleegg.room.CoinType
import com.sy.simpleegg.room.RoomUtil
import com.sy.simpleegg.room.entity.CoinEntity
import com.sy.simpleegg.util.DateTimeUtil
import java.util.Calendar

class FastManageModel: BaseModel(), FastManageContract.Model {
    override suspend fun saveCoins(coins: Long) {
        val coinEntity = CoinEntity().apply {
            type = CoinType.IN
            this.coins = coins
            date = DateTimeUtil.nowDate
            time = DateTimeUtil.nowTime
        }
        RoomUtil.saveCoins(coinEntity)
    }

    override suspend fun getClearData(): MutableList<ClearDataBean>? {
//        val now = Calendar.getInstance()
//        now.add(Calendar.DAY_OF_MONTH, -30)
//        val before: String = DateUtil.getDate(now.time)
//
//        val beforeTime = System.currentTimeMillis() - 30 * 24 * 60 * 60 * 1000
//        val beforeDate: String = DateUtil.getDate(Date(beforeTime))
//        val nowDate: String = DateUtil.getDate(Date())



        return try {
            val calendar = Calendar.getInstance().apply { add(Calendar.DAY_OF_MONTH, -30) }
            val previousDate = calendar.time
//
//        val nowCalenda = Calendar.getInstance()
//        val nowDate = nowCalenda.time
            val coinEntities = RoomUtil.getClearData(DateTimeUtil.formatDate(previousDate, DateTimeUtil.DATE_PATTERN_DATE), DateTimeUtil.nowDate)
            if (coinEntities.isNullOrEmpty()){
                return null
            }
            val dates: MutableList<String> = mutableListOf()
            coinEntities!!.forEach {
                if (it.date.isNullOrEmpty()){
                    return@forEach
                }
                if (dates.indexOf(it.date) == -1){
                    dates.add(it.date!!)
                }
            }

            if (dates.isEmpty()){
                return null
            }

            val result: MutableList<ClearDataBean> = mutableListOf()
            dates.forEach { d ->
                val clearDataBean = ClearDataBean(d, 0)
                coinEntities.forEach { c ->
                    if (d == c.date){
                        clearDataBean.clearCount += c.coins.toLong()
                    }
                }
                result.add(clearDataBean)
            }
            result
        }catch (e: Exception){
            e.printStackTrace()
            logFile("获取清币数据异常：${e.message}")
            null
        }
    }

}